//
//  OauthViewController.swift
//  WEIBO_SWIFT
//
//  Created by 岳挺 on 15/6/28.
//  Copyright © 2015年 yueting. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class OauthViewController: UIViewController,UIWebViewDelegate {
    
    private let Client_ID = "3035627185"
    private let Redirect_URI = "https://www.baidu.com"
    private let Client_SECRET = "1e5a5d5aa7abb279ffd454126140320f"
    private let Grant_TYPE = "authorization_code"
    
    override func loadView() {
        view = web
        title = "新浪微博"
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadOauth()
    }
    
    ///加载授权页面
    func loadOauth (){
        let str = "https://api.weibo.com/oauth2/authorize?client_id=\(Client_ID)&redirect_uri=\(Redirect_URI)"
        
        let url = NSURL(string:str)
        web!.loadRequest(NSURLRequest(URL: url!))
    }
    
    //初始地址：   https://api.weibo.com/oauth2/authorize?client_id=3035627185&redirect_uri=https://www.baidu.com
    //登陆成功地址：https://api.weibo.com/oauth2/authorize
    //授权成功地址：https://www.baidu.com/?code=8c248a22de121328e91930e8feed4eb1
    //取消授权：http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //获得url的完整字符串
        let urlStr = request.URL!.absoluteString
        
        //如果字符串不包含回调地址，继续访问
        if !urlStr.hasPrefix(Redirect_URI){
            return true
        }
        
        //如果url包含回调地址，再次判断
        print("再次判断")
        let query = request.URL!.query!
        let codeStr = "code="
        if query.hasPrefix(codeStr){
            let code = query.substringFromIndex(advance(codeStr.endIndex, 0))
            print("-----------------------CODE-----------------------\(code)")
            print("load token")
            loadAccessToken(code)
        }else{
            print("cancel authorize")
        }
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showInfoWithStatus("loading...")
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //利用授权码获取令牌
    /*token：
    "access_token" = "2.00JI2rJGnSL8_D42ef9113eap6IPFC";
    "expires_in" = 157679999;
    "remind_in" = 157679999;
    
    uid = 5642496629;*/
    //https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00JI2rJGnSL8_D42ef9113eap6IPFC
    func loadAccessToken (authCode : String) {
        let urlStr = "oauth2/access_token"
        let netWorkTool = NetWorkTool.sharedNetWorkTool()
        let params = ["client_id" : Client_ID , "client_secret" : Client_SECRET , "grant_type" : Grant_TYPE , "redirect_uri" : Redirect_URI , "code" : authCode];
        //发送post请求加载
        netWorkTool.POST(urlStr, parameters: params, success: { (_, respone) -> Void in
            //字典转模型加载数据
            UserAccount(dict: respone as! [String : AnyObject]).loadUserInfo({ (account, error) -> () in
                
                //判断数据是否正确
                if account != nil {
                    sharedUserAccount = account
                    NSNotificationCenter.defaultCenter().postNotificationName(notification, object: false)
                }
            })
            }) { (_, error) -> Void in
                print(error)
        }
    }
    
    func close (){
        dismissViewControllerAnimated(true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    ///webview懒加载
    lazy var web : UIWebView? = {
        let w = UIWebView()
        w.delegate = self
        return w
    }()
}
